import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

# 1. 生成示例数据
t = np.linspace(0, 10, 1000)  # 时间轴
mean_velocity = 2.5          # 平均速度
fluctuation = 0.5 * np.sin(2 * np.pi * 1 * t)  # 正弦波动
noise = 0.1 * np.random.randn(len(t))        # 高斯噪声
velocity = mean_velocity + fluctuation + noise

# 2. 数据预处理：去除线性趋势
detrended = signal.detrend(velocity)

# 3. 计算脉动量 (RMS)
mean_detrended = np.mean(detrended)
rms_fluctuation = np.sqrt(np.mean(detrended**2))

print(f"平均速度: {mean_velocity:.3f} m/s")
print(f"脉动量 RMS: {rms_fluctuation:.3f} m/s")

# 4. 可视化
plt.figure(figsize=(10, 6))
plt.subplot(3, 1, 1)
plt.plot(t, velocity, label='原始信号')
plt.ylabel('速度 (m/s)')
plt.legend()

plt.subplot(3, 1, 2)
plt.plot(t, detrended, label='去趋势信号', color='orange')
plt.ylabel('速度 (m/s)')
plt.legend()

plt.subplot(3, 1, 3)
plt.plot(t, detrended**2, label='波动平方', color='green')
plt.xlabel('时间 (s)')
plt.ylabel('平方值')
plt.legend()

plt.tight_layout()
plt.show()

# 还需要加入前置的带通滤波、频谱分析